package com.plian.system.service.pm.propertytransaction.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.GsonBuilder;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.plian.Tools.*;
import com.plian.Tools.office.WordUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.cache.UserCache;
import com.plian.system.common.status.MyCustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.entity.pm.ownershipstructureback.OwnershipStructureBack;
import com.plian.system.entity.pm.propertytransaction.PropertyTransaction;
import com.plian.system.entity.pm.publiclist.PublicList;
import com.plian.system.entity.pm.subjectevaluation.SubjectEvaluation;
import com.plian.system.entity.sys.ApprovalMessage;
import com.plian.system.mapper.pm.propertytransaction.PropertyTransactionMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.model.page.Page;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.properties.GzwProperties;
import com.plian.system.service.pm.ownershipstructureback.IOwnershipStructureBackService;
import com.plian.system.service.pm.property.IPropertyBasicsService;
import com.plian.system.service.pm.propertytransaction.IPropertyTransactionService;
import com.plian.system.service.pm.publiclist.IPublicListService;
import com.plian.system.service.pm.subjectEvaluation.ISubjectEvaluationService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.message.IApprovalMessageService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.user.ISysUserService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.ownershipstructureback.OwnershipStructureBackVO;
import com.plian.system.vo.pm.propertytransaction.PropertyTransactionVO;
import com.plian.system.vo.pm.publiclist.PublicListVO;
import com.plian.system.vo.pm.subjectevaluation.SubjectEvaluationVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.pm.ownershipstructureback.OwnershipStructureBackWrapper;
import com.plian.system.wrapper.pm.propertytransaction.PropertyTransactionWrapper;
import com.plian.system.wrapper.pm.publiclist.PublicListWrapper;
import com.plian.system.wrapper.pm.subjectevaluation.SubjectEvaluationWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;
import static com.plian.system.constant.sys.FormTypeConstant.CQZC_PROPERTYTRANSACTION_FORM;

/**
 * 产权交易备案主表 服务实现类
 *
 * @author gangan
 * @since 2019-10-12
 */
@Slf4j
@Service
@AllArgsConstructor
public class PropertyTransactionServiceImpl extends BaseServiceImpl<PropertyTransactionMapper, PropertyTransaction> implements IPropertyTransactionService, BaseFlowService {

    private ISubjectEvaluationService subjectEvaluationService;
    private IOwnershipStructureBackService ownershipStructureBackService;
    private IPublicListService publicListService;
    private IFormCodeService formCodeService;
    private PropertyTransactionMapper propertyTransactionMapper;
    private BaseInfoDao baseInfoDao;
    private Environment environment;
    private FormWorkflowService formWorkflowService;

    private PublicListWrapper publicListWrapper;

    private SubjectEvaluationWrapper subjectEvaluationWrapper;

    private OwnershipStructureBackWrapper ownershipStructureBackWrapper;

    private PropertyTransactionWrapper propertyTransactionWrapper;

    private GzwProperties gzwProperties;

    private FileService fileService;

    private IOrgService orgService;

    private ISysUserService userService;

    private IApprovalMessageService approvalMessageService;

    private final String SUNSHINE_DATASOURCE_TYPE = "5";

    private IPropertyBasicsService propertyBasicsService;



    @Override
    public ObjResult submit(PropertyTransactionVO propertyTransactionVO) {
        Boolean checkResult = false;

        if (!(Optional.ofNullable(propertyTransactionVO.getStatus()).isPresent() && propertyTransactionVO.getStatus() == FormStatusConstant.STASH)) {
            checkResult = checkIsExisted(propertyTransactionVO.getId(), propertyTransactionVO.getCode());
        }

        if (checkResult) {
            if (StringUtil.isBlank(propertyTransactionVO.getVersion())) {
                propertyTransactionVO.setVersion("1");
            }
            if (Optional.ofNullable(propertyTransactionVO.getStatus()).isPresent() && propertyTransactionVO.getStatus() != FormStatusConstant.STASH) {
                propertyTransactionVO.setFormType(String.valueOf(FormTypeConstant.CQZC_PROPERTYTRANSACTION_FORM));
            }
            PropertyTransaction propertyTransaction = new PropertyTransaction();
            BeanUtils.copyProperties(propertyTransactionVO, propertyTransaction);
            boolean result = saveOrUpdate(propertyTransaction);
            if (result) {
                propertyTransactionVO.setId(propertyTransaction.getId());
                saveChild(propertyTransactionVO);
                List<HashMap> listDoc = propertyTransactionVO.getList_doc();
                fileService.edit(propertyTransaction.getId().toString(), listDoc);
            }
            return result ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
        } else {
            return new ObjResult(CommonCode.FAIL);
        }
    }

    @Override
    public boolean saveOrUpdate(PropertyTransaction propertyTransaction) {
        if (!Optional.ofNullable(propertyTransaction.getId()).isPresent()) {
            propertyTransaction.setVersion("1");
            propertyTransaction.setFormType(String.valueOf(FormTypeConstant.CQZC_PROPERTYTRANSACTION_FORM));
            propertyTransaction.setCode(formCodeService.getCode(FormTypeConstant.CQZC_PROPERTYTRANSACTION_FORM));
        }

        if (Optional.ofNullable(propertyTransaction.getStatus()).isPresent() && propertyTransaction.getStatus() != -1) {
            propertyTransaction.setStatus(propertyTransaction.getStatus());
        }

        return super.saveOrUpdate(propertyTransaction);
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            PropertyTransaction propertyTransaction = getById(id);
            if (propertyTransaction == null) {
                return false;
            } else if (propertyTransaction.getStatus() != null &&
                    (propertyTransaction.getStatus() != FormStatusConstant.STASH && propertyTransaction.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }
        return super.deleteLogic(ids);
    }


    @Override
    public HashMap<String, Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW, null);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String, Object>();
    }



    @Override
    public Boolean reject(String id, int formState, String comment) {
        return handleStatus(Long.valueOf(id), formState, comment);
    }


    @Override
    public Boolean checkIsExisted(Long id, String code) {
        if (Optional.ofNullable(code).isPresent()) {
            PropertyTransaction propertyTransaction = new PropertyTransaction();
            propertyTransaction.setCode(code);
            if (Optional.ofNullable(getOne(Condition.getQueryWrapper(propertyTransaction))).isPresent()) {
                if (id == null || !id.equals(getOne(Condition.getQueryWrapper(propertyTransaction)).getId())) {
                    return false;
                }
            }
        }
        return true;
    }


    @Override
    public ObjResult checkSubmit(PropertyTransaction propertyTransaction) {

        if (!checkIsExisted(propertyTransaction.getId(), propertyTransaction.getCode())) {
//            return R.fail("单据编码已存在");
            return new ObjResult(MyCustomCode.BILL_ALREADY_EXISTS2);
        }

        return null;
    }

    @Override
    public R<PropertyTransactionVO> getDetailObj(PropertyTransactionVO propertyTransactionVO) {
        return R.data(setChild(propertyTransactionVO));
    }

    @Override
    public PropertyTransactionVO setChild(PropertyTransactionVO propertyTransactionVO) {
        if (Optional.ofNullable(propertyTransactionVO).isPresent()) {
            propertyTransactionVO.setPublicListVO(publicListWrapper.entityToVO(publicListService
                    .list(new LambdaQueryWrapper<PublicList>().eq(PublicList::getPropertyTransactionId, propertyTransactionVO.getId()))));
            propertyTransactionVO.setSubjectEvaluationVO(subjectEvaluationWrapper.entityToVO(subjectEvaluationService
                    .list(new LambdaQueryWrapper<SubjectEvaluation>().eq(SubjectEvaluation::getPropertyTransactionId, propertyTransactionVO.getId()))));
            propertyTransactionVO.setOwnershipStructureBackVO(ownershipStructureBackWrapper.entityToVO(ownershipStructureBackService
                    .list(new LambdaQueryWrapper<OwnershipStructureBack>().eq(OwnershipStructureBack::getPropertyTransId, propertyTransactionVO.getId()))));
        }
        return propertyTransactionVO;
    }


    @Override
    public Boolean saveChild(PropertyTransactionVO propertyTransactionVO) {
        try {
            List<PublicListVO> publicListVO = propertyTransactionVO.getPublicListVO();
            for (PublicListVO pubVo : publicListVO) {
                if (Optional.ofNullable(pubVo.getIsDeleted()).isPresent() && pubVo.getIsDeleted().intValue() == 1) {
                    publicListService.removeById(pubVo.getId());
                } else {
                    pubVo.setPropertyTransactionId(propertyTransactionVO.getId().toString());
                    publicListService.saveOrUpdate(pubVo);
                }
            }
            List<SubjectEvaluationVO> subjectEvaluationVO = propertyTransactionVO.getSubjectEvaluationVO();
            for (SubjectEvaluationVO subVo : subjectEvaluationVO) {
                if (Optional.ofNullable(subVo.getIsDeleted()).isPresent() && subVo.getIsDeleted().intValue() == 1) {
                    subjectEvaluationService.removeById(subVo.getId());
                } else {
                    subVo.setPropertyTransactionId(propertyTransactionVO.getId().toString());
                    subjectEvaluationService.saveOrUpdate(subVo);
                }
            }

            List<OwnershipStructureBackVO> ownershipStructureBackVO = propertyTransactionVO.getOwnershipStructureBackVO();
            for (OwnershipStructureBackVO ownvo : ownershipStructureBackVO) {
                if (Optional.ofNullable(ownvo.getIsDeleted()).isPresent() && ownvo.getIsDeleted().intValue() == 1) {
                    ownershipStructureBackService.removeById(ownvo.getId());
                } else {
                    ownvo.setPropertyTransId(propertyTransactionVO.getId().toString());
                    ownershipStructureBackService.saveOrUpdate(ownvo);
                }
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
        return true;
    }

    /**
     * @param formIds
     * @return
     */
    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<PropertyTransaction> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PropertyTransaction::getId, Func.toLongList(org.apache.commons.lang3.StringUtils.join(formIds, StringPool.COMMA)));
        List<PropertyTransaction> propertyTransaction = list(queryWrapper);
        List<PropertyTransactionVO> propertyTransactionVOS = propertyTransactionWrapper.entityToVO(propertyTransaction);
        List<PageData> pageDataList = new ArrayList<>();
        try {
            if (CollectionUtil.isNotEmpty(propertyTransactionVOS)) {
                for (PropertyTransactionVO vo : propertyTransactionVOS) {
                    vo.setUNITNAME(vo.getReportCompanyName());
                    vo.setAPPLICANTNAME(vo.getCreateUserName());
                    PageData pd = new PageData();
                    pd.put("orgName", vo.getReportCompanyName());
                    ObjectMapper mapper = new ObjectMapper();
                    String json = new GsonBuilder().setDateFormat(DateUtil.PATTERN_DATETIME).create().toJson(vo);
                    pd.putAll(mapper.readValue(json, new TypeReference<HashMap<String, String>>() {
                    }));
                    pageDataList.add(pd);
                }
            }
            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(CQZC_PROPERTYTRANSACTION_FORM);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED, null);
    }

    @Override
    public File buildword(String id, HttpServletResponse response) {
        PropertyTransactionVO bean = propertyTransactionWrapper.entityToVO(getById(id));
        File file = null;
        try {
            if (bean != null) {
                Map<String, Object> data = new HashMap<>(16);
                data.put("filingId", bean.getFilingId());
                data.put("reportCompanyName", bean.getReportCompanyName());
                data.put("transferorName", bean.getTransferorName());
                PageData findbycode = baseInfoDao.findbycode(bean.getTransferorNatureId());
                data.put("transferorNatureName", findbycode != null ? findbycode.getString("name") : "");
                data.put("agencyApprovalDate", bean.getAgencyApprovalDate());
                PageData type = baseInfoDao.findbycode(bean.getActivityTypeId());
                data.put("activityTypeName", type != null ? type.getString("name") : "");
                data.put("transferTarget", bean.getTransferTarget());
                PageData name = baseInfoDao.findbycode(bean.getTransactionMeansId());
                data.put("transactionMeansName", name != null ? name.getString("name") : "");
                PageData payName = baseInfoDao.findbycode(bean.getTransferPaymentId());
                data.put("transferPaymentName", payName != null ? payName.getString("name") : "");
                data.put("paidPrice", bean.getPaidPrice());
                data.put("transfereeName", bean.getTransfereeName());
                PageData natureName = baseInfoDao.findbycode(bean.getTransfereeNatureId());
                data.put("transfereeNatureName", natureName != null ? natureName.getString("name") : "");
                data.put("approvedTime", bean.getApprovedTime());
                data.put("approvedUser", bean.getApprovedUserName());

                PageData pageData = new PageData();
                pageData.put("bookValue", "");
                pageData.put("assessedValue", "");
                pageData.put("evaluationAgencyReport", "");
                pageData.put("listingPrice", "");
                pageData.put("dealPrice", "");
                pageData.put("propertyInstitutionName", "");

                SubjectEvaluation subjectEvaluation = new SubjectEvaluation();
                subjectEvaluation.setPropertyTransactionId(String.valueOf(bean.getId()));
                List<SubjectEvaluationVO> subjectEvaluationVOS = subjectEvaluationWrapper.entityToVO(subjectEvaluationService.list(Condition.getQueryWrapper(subjectEvaluation)));
                if (CollectionUtil.isNotEmpty(subjectEvaluationVOS)) {
                    data.put("subjectEvaluationVOS", subjectEvaluationVOS);
                } else {
                    data.put("subjectEvaluationVOS", pageData);
                }

                PublicList publicList = new PublicList();
                publicList.setPropertyTransactionId(String.valueOf(bean.getId()));
                List<PublicListVO> publicListVOS = publicListWrapper.entityToVO(publicListService.list(Condition.getQueryWrapper(publicList)));
                data.put("transactionFlag", 2);
                if (Optional.ofNullable(bean.getTransactionMeansId()).isPresent() && "062003".equals(bean.getTransactionMeansId())) {
                    data.put("transactionFlag", 1);
                    if (CollectionUtil.isNotEmpty(publicListVOS)) {
                        for (PublicListVO publicListVO : publicListVOS) {
                            publicListVO.setContractSigningDate(bean.getTransactionDate());
                            publicListVO.setDef1("1");
                        }
                        data.put("publicListVOS", publicListVOS);
                    } else {
                        data.put("publicListVOS", pageData);
                    }
                }
                if (Optional.ofNullable(bean.getTransactionMeansId()).isPresent() && !"062003".equals(bean.getTransactionMeansId())) {
                    if (CollectionUtil.isNotEmpty(publicListVOS)) {
                        data.put("publicListVOS", publicListVOS);
                    } else {
                        data.put("publicListVOS", pageData);
                    }
                }

                String realPath = environment.getProperty("doc.path") + id + ".doc";
                //备案编号
                String filingId = bean.getFilingId();
                if (filingId == null) {
                    file = WordUtil.generateWord(data, realPath, "propertyTransaction.doc", "propertyTransaction.ftl");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
                } else {
                    file = WordUtil.generateWord(data, realPath, filingId + ".doc", "propertyTransaction.ftl");
                    String fileName = new String(file.getName().getBytes("GB2312"), "ISO_8859_1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
                }
                InputStream inputStream = new FileInputStream(file);
                // 激活下载操作
                OutputStream os = response.getOutputStream();
                // 循环写入输出流
                byte[] b = new byte[2048];
                int length;
                while ((length = inputStream.read(b)) > 0) {
                    os.write(b, 0, length);
                }
                // 这里主要关闭。
                os.close();
                inputStream.close();
            }

        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return file;
    }

    @Override
    public File createReceptFile(Long id) {
        try {
            int lenth = 0;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PropertyTransactionVO bean = propertyTransactionWrapper.entityToVO(getById(id));
            bean = setChild(bean);
            lenth = bean.getSubjectEvaluationVO() == null ? 0 : bean.getSubjectEvaluationVO().size();
            String[][] subjectEvaluation = new String[lenth][4];
            for (int i = 0; i < lenth; i++) {
                subjectEvaluation[i][0] = bean.getSubjectEvaluationVO().get(i).getBookValue() == null ? "-" : bean.getSubjectEvaluationVO().get(i).getBookValue().toString();
                subjectEvaluation[i][1] = bean.getSubjectEvaluationVO().get(i).getAssessedValue() == null ? "-" : bean.getSubjectEvaluationVO().get(i).getAssessedValue().toString();
                subjectEvaluation[i][2] = bean.getSubjectEvaluationVO().get(i).getEvaluationBaseDate() == null ? "-" : sdf.format(bean.getSubjectEvaluationVO().get(i).getEvaluationBaseDate());
                subjectEvaluation[i][3] = bean.getSubjectEvaluationVO().get(i).getEvaluationAgencyReport() == null ? "-" : bean.getSubjectEvaluationVO().get(i).getEvaluationAgencyReport();
            }

            lenth = bean.getPublicListVO() == null ? 0 : bean.getPublicListVO().size();
            String[][] publicList = new String[lenth][4];
            for (int i = 0; i < lenth; i++) {
                publicList[i][0] = bean.getPublicListVO().get(i).getListingPrice() == null ? "-" : bean.getPublicListVO().get(i).getListingPrice().toString();
                publicList[i][1] = bean.getPublicListVO().get(i).getDealPrice() == null ? "-" : bean.getPublicListVO().get(i).getDealPrice().toString();
                publicList[i][2] = bean.getPublicListVO().get(i).getContractSigningDate() == null ? "-" : sdf.format(bean.getPublicListVO().get(i).getContractSigningDate());
                ;
                publicList[i][3] = bean.getPublicListVO().get(i).getPropertyInstitutionName() == null ? "-" : bean.getPublicListVO().get(i).getPropertyInstitutionName().toString();
            }
            Document document = new Document(com.itextpdf.text.PageSize.A4, 90, 83, 30, 40);
            FileOutputStream fs;
            BaseFont bfHeiTi;
            BaseFont bfST;
            BaseFont test;
            BaseFont bfbt;

            File pdffile = File.createTempFile(id.toString(), ".pdf");
            if (pdffile.exists()) {
                pdffile.delete();
            }
            fs = new FileOutputStream(pdffile.getPath());//getAbsolutePath
            PdfWriter.getInstance(document, fs);
            // 打开文档
            document.open();
            bfST = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfHeiTi = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            bfbt = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            test = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 创建了一页
            Font font_Zhengwen = new Font(bfST, 10.0f, Font.NORMAL, BaseColor.BLACK);
            // 添加标题
            Font font_Biaoti = new Font(bfHeiTi, 20.0f, Font.BOLD, BaseColor.BLACK);
            Font font_biaotou2 = new Font(bfbt, 10.0f, Font.NORMAL, BaseColor.BLACK);


            // 创建一个段落
            String title = "市属企业资产转让(划转)备案表";
            Paragraph biaoti = new Paragraph(title, font_Biaoti);
            biaoti.setAlignment(1);
            biaoti.setSpacingAfter(20f);
            document.add(biaoti);
            String title1 = "备案编号: " + (bean.getFilingId() == null ? "" : bean.getFilingId()) + "                               金额单位：万元";
            Paragraph biaoti1 = new Paragraph(title1, font_biaotou2);
            biaoti1.setAlignment(1);
//            biaoti1.setSpacingAfter(20f);
            document.add(biaoti1);
            float[] widths = {120f, 300f};// 设置表格的列宽
            PdfPTable table = new PdfPTable(widths);// 建立一个pdf表格
            table.setSpacingBefore(10f);// 设置表格上面空白宽度
            table.setSpacingAfter(0f);// 设置表格下面空白宽度
            table.setTotalWidth(420);// 设置表格的宽度
            PdfPCell cell = new PdfPCell();
            PdfPCell cell2 = new PdfPCell();
            cell.setMinimumHeight(30f);
            cell2.setMinimumHeight(30f);
            cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPaddingTop(5);
            cell.setPaddingBottom(5);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setPaddingTop(5);
            cell2.setPaddingBottom(5);
            table.setLockedWidth(true);

            //正式开始
            cell.setPhrase(new Paragraph("填报单位", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getReportCompanyName(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("转让方(划转方)名称", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getTransferorName(), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("转让方(划转方)\n" +
                    "企业性质\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            PageData p = baseInfoDao.findbycode(bean.getTransferorNatureId());
            if (p != null) {
                cell2.setPhrase(new Paragraph(p.getString("name"), font_Zhengwen));
            } else {
                cell2.setPhrase(new Paragraph("", font_Zhengwen));
            }

            table.addCell(cell2);

            cell.setPhrase(new Paragraph("经济行为决策机构\n" +
                    "及批准文件日期\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(String.valueOf(bean.getAgencyApprovalDate()), font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("经济行为类型", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            PageData type = baseInfoDao.findbycode(bean.getActivityTypeId());
            String t = "-";
            if (type != null) {
                t = type.getString("name");
            }

            cell2.setPhrase(new Paragraph(t, font_Zhengwen));
            table.addCell(cell2);

            cell.setPhrase(new Paragraph("转让(划转)标的", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getTransferTarget(), font_Zhengwen));
            table.addCell(cell2);

            document.add(table);//第一组结束

            float[] widths2 = {120f, 60f, 60f, 60f, 120f};// 设置表格的列宽
            PdfPTable table2 = new PdfPTable(widths2);// 建立一个pdf表格
            table2.setSpacingBefore(0f);// 设置表格上面空白宽度
            table2.setSpacingAfter(0f);// 设置表格下面空白宽度
            table2.setTotalWidth(420);// 设置表格的宽度
            table2.setLockedWidth(true);

            cell.setPhrase(new Paragraph("转让(划转)标\n" +
                    "的评估情况\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setRowspan(subjectEvaluation.length + 1);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("账面值", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setRowspan(1);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("评估值", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("评估基准日", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            cell.setPhrase(new Paragraph("资产评估机构及评估报告文号", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table2.addCell(cell);
            lenth = subjectEvaluation.length;
            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 4; j++) {
                    if (i < subjectEvaluation.length) {
                        String s = subjectEvaluation[i][j];
                        if (s == null) {
                            s = "";
                        }
                        cell2.setPhrase(new Paragraph(s, font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setColspan(1);
                    cell2.setRowspan(1);
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table2.addCell(cell2);
                }
            }
            document.add(table2);

            PdfPTable table3 = new PdfPTable(widths);// 建立一个pdf表格
            table3.setSpacingBefore(0f);// 设置表格上面空白宽度
            table3.setSpacingAfter(0f);// 设置表格下面空白宽度
            table3.setTotalWidth(420);// 设置表格的宽度
            table3.setLockedWidth(true);
            cell.setPhrase(new Paragraph("交易方式", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table3.addCell(cell);
            cell2.setPhrase(new Paragraph(baseInfoDao.findbycode(bean.getTransactionMeansId()).getString("name"), font_Zhengwen));
            cell2.setColspan(1);
            cell2.setRowspan(1);
            table3.addCell(cell2);
            document.add(table3);

            PdfPTable table4 = new PdfPTable(widths2);// 建立一个pdf表格
            table4.setSpacingBefore(0f);// 设置表格上面空白宽度
            table4.setSpacingAfter(0f);// 设置表格下面空白宽度
            table4.setTotalWidth(420);// 设置表格的宽度
            table4.setLockedWidth(true);
            lenth = publicList.length;
            cell.setPhrase(new Paragraph("进场公开挂\n" +
                    "牌交易情况\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setRowspan(lenth + 1);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("挂牌价格", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setRowspan(1);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("成交价格", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("合同签订（生效）日", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table4.addCell(cell);
            cell.setPhrase(new Paragraph("产权交易机构名称", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            table4.addCell(cell);

            for (int i = 0; i < lenth; i++) {
                for (int j = 0; j < 4; j++) {
                    if (i < publicList.length) {
                        cell2.setPhrase(new Paragraph(publicList[i][j], font_Zhengwen));
                    } else {
                        cell2.setPhrase(new Paragraph("", font_Zhengwen));
                    }
                    cell2.setColspan(1);
                    cell2.setRowspan(1);
                    cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table4.addCell(cell2);
                }
            }
            document.add(table4);

            float[] widths3 = {90f, 30f, 60f, 60f, 60f, 60f, 60f};// 设置表格的列宽
            PdfPTable table5 = new PdfPTable(widths3);// 建立一个pdf表格
            table5.setSpacingBefore(0f);// 设置表格上面空白宽度
            table5.setSpacingAfter(0f);// 设置表格下面空白宽度
            table5.setTotalWidth(420);// 设置表格的宽度
            table5.setLockedWidth(true);
            cell.setPhrase(new Paragraph("转让价款支付方式", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(2);
            cell.setRowspan(1);
            table5.addCell(cell);
            cell2.setPhrase(new Paragraph(baseInfoDao.findbycode(bean.getTransferPaymentId()).getString("name"), font_Zhengwen));
            cell2.setColspan(3);
            cell2.setRowspan(1);
            table5.addCell(cell2);

            cell.setPhrase(new Paragraph("实收价款", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table5.addCell(cell);
            cell2.setPhrase(new Paragraph(String.valueOf(bean.getPaidPrice()), font_Zhengwen));
            cell2.setColspan(1);
            cell2.setRowspan(1);
            table5.addCell(cell2);

            cell.setPhrase(new Paragraph("受让方(划入方)名称", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table5.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getTransfereeName(), font_Zhengwen));
            cell2.setColspan(6);
            cell2.setRowspan(1);
            table5.addCell(cell2);

            cell.setPhrase(new Paragraph("受让方(划入方)性质", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table5.addCell(cell);
            cell2.setPhrase(new Paragraph(baseInfoDao.findbycode(bean.getTransfereeNatureId()).getString("name"), font_Zhengwen));
            cell2.setColspan(6);
            cell2.setRowspan(1);
            table5.addCell(cell2);

            cell.setPhrase(new Paragraph("备案资\n" +
                    "料目录\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table5.addCell(cell);
            cell2.setPhrase(new Paragraph(bean.getRecordingDirectory(), font_Zhengwen));
            cell2.setColspan(6);
            cell2.setRowspan(1);
            table5.addCell(cell2);

            document.add(table5);

            float[] widths4 = {90f, 165f, 165f};// 设置表格的列宽
            PdfPTable table6 = new PdfPTable(widths4);// 建立一个pdf表格
            table6.setSpacingBefore(0f);// 设置表格上面空白宽度
            table6.setSpacingAfter(0f);// 设置表格下面空白宽度
            table6.setTotalWidth(420);// 设置表格的宽度
            table6.setLockedWidth(true);

            cell.setPhrase(new Paragraph("\n意\n\n" +
                    "见\n\n" +
                    "及\n\n" +
                    "签\n\n" +
                    "章\n\n", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setColspan(1);
            cell.setRowspan(1);
            table6.addCell(cell);
            cell2.setPhrase(new Paragraph("\n" +
                    "填报单位意见\n\n\n" +
                    "\n" +
                    "                              同意上报\n" +
                    "\n" +
                    "                                        （盖章）\n\n\n" +
                    "                                              年       月       日", font_Zhengwen));
            cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell2.setColspan(1);
            cell2.setRowspan(1);
            table6.addCell(cell2);

            cell.setPhrase(new Paragraph("\n" +
                    "国资监管部门意见\n\n\n" +
                    "\n" +
                    "                              同意备案\n" +
                    "\n" +
                    "                                        （盖章）\n\n\n" +
                    "                                              年       月       日", font_biaotou2));
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell.setColspan(1);
            cell.setRowspan(1);
            table6.addCell(cell);
            document.add(table6);
            document.close();

            return pdffile;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return null;
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id           主键
     * @param updateStatus 判断状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus, String comment) {
        try {
            PropertyTransaction propertyTransaction = getById(id);
            if (updateStatus == FormStatusConstant.FINISH) {
                propertyTransaction.setApprovedUser(TokenUtil.getTokenUserId());
                propertyTransaction.setApprovedTime(DateUtil.now());
                if ("是".equals(propertyTransaction.getIfFiling())) {
                    String code = formCodeService.getFilingCode(FormTypeConstant.CQZC_PROPERTYTRANSACTION_FORM);
                    propertyTransaction.setFilingId(gzwProperties.getCodeStartName() + "转备〔" + code.substring(0, 4) + "〕（" + code.substring(code.length() - 3, code.length()) + "）号");
                }
            }
            propertyTransaction.setStatus(updateStatus);
            if (YthConstant.DATA_NINGBO.equals(propertyTransaction.getDataSource())) {
                if (updateStatus == FormStatusConstant.FINISH || updateStatus == FormStatusConstant.REJECT) {
                    ApprovalMessage approvalMessage = new ApprovalMessage();
                    approvalMessage.setDataSourceId(propertyTransaction.getDataSourceId());
                    approvalMessage.setOpinion(comment);
                    approvalMessage.setIsApprove(updateStatus == FormStatusConstant.FINISH ? 2 : 1);
                    approvalMessage.setIsSend(1);
                    approvalMessage.setDataSourceType(YthConstant.DATA_NINGBO);
                    approvalMessage.setFilingUserName(UserCache.userIdToName(TokenUtil.getTokenUserId()));
                    approvalMessage.setFormType(Integer.valueOf(propertyTransaction.getFormType()));
                    approvalMessage.setFilingCode(propertyTransaction.getCode());
                    approvalMessageService.save(approvalMessage);
                }
            }
            updateById(propertyTransaction);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw e;
        }
    }

    @Override
    public ListResult<PageData> reportList(PageData pd) {
        Page page = new Page(false, pd);
        try {
            List<PageData> list = propertyTransactionMapper.reportListPage(page);
            ListResult listResult = new ListResult(CommonCode.SUCCESS);
            listResult.setList(list);
            listResult.setTotal(page.getTotal());
            return listResult;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new MyRuntimeException();
        }
    }

    @Override
    public Boolean finish(String id) {
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH, "审批成功");
    }

    /**
     * 获得产权交易报表
     *
     * @param pd
     */
    @Override
    public ObjResult propertyTable(PageData pd) {
        ObjResult objResult;
        List<PageData> pagesone = new ArrayList<>();
        List<PageData> pagestwo = new ArrayList<>();
        List<PageData> pagesthree = new ArrayList<>();
        PageData pd2 = new PageData();

        ArrayList<String> orgIds = (ArrayList<String>) pd.get("orgIds");
        for (String orgId : orgIds) {
            pd.put("orgId", orgId);
            List<PageData> list = propertyTransactionMapper.orgidForList(pd);
            for (PageData page : list) {
                PageData publiclist = propertyTransactionMapper.dateForList(page);
                PageData subject = propertyTransactionMapper.dateForList2(page);
                if (publiclist != null) {
                    Set set = publiclist.keySet();
                    Iterator iterator = set.iterator();
                    while (iterator.hasNext()) {
                        String key = (String) iterator.next();
                        String value = publiclist.getString(key);
                        page.put(key, value);
                    }
                }
                if (subject != null) {
                    Set set = subject.keySet();
                    Iterator iterator = set.iterator();
                    while (iterator.hasNext()) {
                        String key = (String) iterator.next();
                        String value = subject.getString(key);
                        page.put(key, value);
                    }
                }
                //contractSigningDate 时间2020-10-30T00:00:00.000+0800
                String contractSigningDate = page.getString("contractSigningDate");
                if (contractSigningDate != null) {
                    contractSigningDate = PropertyTransactionServiceImpl.covnDate(contractSigningDate);
                } else {
                    contractSigningDate = "";
                }
                page.put("contractSigningDate", contractSigningDate);
                String activityTypeId = page.getString("activityTypeId");
                //产权转让
                if ("047001".equals(activityTypeId)) {
                    pagesone.add(page);
                } else if ("047002".equals(activityTypeId)) {
                    pagestwo.add(page);
                } else if ("047003".equals(activityTypeId)) {
                    pagesthree.add(page);
                }
            }
        }
        pd2.put("property", pagesone);
        pd2.put("assets", pagestwo);
        pd2.put("invest", pagesthree);
        objResult = new ObjResult(CommonCode.SUCCESS);
        objResult.setPageData(pd2);
        return objResult;
    }


    private static String covnDate(String dateTime) {
        DateFormat df2 = null;
        Date date1 = null;
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            Date date = df.parse(dateTime);
            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            date1 = df1.parse(date.toString());
            df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            dateTime = dateTime.substring(0, 10);
            return dateTime;
        }
        return df2.format(date1);
    }

    /**
     * 接收数字宁波项目信息
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public String savePropertyTransactionServiceList(String data) {
        YthResult ythResult = new YthResult();
        //成功的id集合
        List<String> successIds = new ArrayList<>();
        //失败的id集合
        List<String> failIds = new ArrayList<>();
        //失败的原因
        List<String> failReasons = new ArrayList<>();
        //将json字符串转换成list
        List<PropertyTransactionVO> dataList = JSON.parseArray(data, PropertyTransactionVO.class);
        //判断list是否为空
        if (CollectionUtil.isNotEmpty(dataList)) {
            //根据datasourceIds 查询出所有的数据
            List<PropertyTransaction> list = list(new LambdaQueryWrapper<PropertyTransaction>()
                    .in(PropertyTransaction::getDataSourceId, dataList.stream()
                            .map(PropertyTransaction::getDataSourceId).toArray()));
            //如果数据库中有数据，就更新，没有就新增
            for (PropertyTransactionVO entity : dataList) {
                String dataSourceId = entity.getDataSourceId();
                if (CollectionUtil.isNotEmpty(list)) {
                    List<String> olIds = list.stream().map(PropertyTransaction::getDataSourceId).collect(Collectors.toList());
                    //判断数据库中是否有数据
                    if (olIds.contains(dataSourceId)) {
                        for (PropertyTransaction oldEntity : list) {
                            if (dataSourceId.equals(oldEntity.getDataSourceId())) {
                                successIds.add(dataSourceId);
                                entity.setId(oldEntity.getId());
                                entity.setDataSource(YthConstant.DATA_NINGBO);
                                extracted(entity);
                                submit(entity);
                                list.remove(oldEntity);
                                break;
                            }
                        }
                    } else {
                        //如果数据库中没有数据，就新增
                        entity.setDataSource(YthConstant.DATA_NINGBO);
                        extracted(entity);
                        submit(entity);
                        successIds.add(entity.getDataSourceId());
                    }
                } else {
                    entity.setDataSource(YthConstant.DATA_NINGBO);
                    extracted(entity);
                    submit(entity);
                    successIds.add(entity.getDataSourceId());
                }
            }
        } else {
            failReasons.add("数据为空");
        }
        ythResult.setSuccessIds(successIds);
        ythResult.setFailIds(failIds);
        ythResult.setFailReason(org.apache.commons.lang3.StringUtils.join(failReasons, ";"));
        //ythResult转换成json字符串
        return JSON.toJSONString(ythResult);
    }

    /**
     * 将数字宁波过来的数据人员id，
     *
     * @param entity
     */
    private void extracted(PropertyTransactionVO entity) {
        Map<String, String> orgSourceIds = orgService.getSourceId();
        Map<String, String> userSourceIds = userService.getSourceId();

        String reportCompanyId = orgSourceIds.get(entity.getReportCompanyId());
        String createUser = userSourceIds.get(entity.getCreateUser());
        if (org.apache.commons.lang3.StringUtils.isNotBlank(reportCompanyId)) {
            entity.setReportCompanyId(reportCompanyId);
            entity.setCreateCompanyId(reportCompanyId);
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(createUser)) {
            entity.setCreateUser(createUser);
            entity.setUpdateUser(createUser);
        }
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
    }

}
